import { message, Switch } from 'antd';
import React, { useState } from 'react';
import { Type } from '../../../../features/util/dictionary';

interface Props {
    /**开关的初始状态 */
    checked?: boolean

    /**开关所在的表格项内容 */
    params?: any

    /**远程请求函数 */
    remote: Function

    /**开关成功变化时，调用此函数 */
    onChange?: Function

    /**开关为真时的展示文本 */
    onText?: string

    /**开关为假时的展示文本 */
    offText?: string

    /**开关显示文本的对象 */
    dictionary?: Type[]

    /**开关提示信息前缀：xxxx成功/失败 */
    promptPrefix?: string

    /**开关请求成功的回调函数 */
    onSuccess?: Function

    /**开关请求失败的回调函数 */
    onFail?: Function

    /**请求成功时不使用默认提示消息 */
    isNotSuccessAlt?: boolean

    /**请求失败时不使用默认提示消息 */
    isNotFailAlt?: boolean
}

const RemoteSwitch: React.FC<Props> = ({
    checked,
    params,
    remote,
    onChange,
    onText,
    offText,
    dictionary,
    promptPrefix,
    onSuccess,
    onFail,
    isNotSuccessAlt = false,
    isNotFailAlt = false,
}) => {
    console.debug('RemoteSwitch');

    const [isLoading, setIsLoading] = useState(false);
    const [isDisabled, setIsDisabled] = useState(false);
    const [isChecked, setIsChecked] = useState<boolean>(() => {
        if (typeof checked !== 'undefined') {
            return checked;
        } else {
            return true
        }
    });
    const [checkedChildren] = useState(() => {
        return onText || dictionary?.find((item: Type) => item.value)?.name || '开启'
    })
    const [unCheckedChildren] = useState(() => {
        return offText || dictionary?.find((item: Type) => !item.value)?.name || '关闭'
    })

    function handleChange(checked: boolean) {
        if (onChange) {
            onChange(checked);
        }
    }

    async function handleClick(checked: boolean) {
        if (remote) {
            setIsLoading(true);
            setIsDisabled(true);
            let promptMsg = promptPrefix || '';
            promptMsg += checked ? checkedChildren : unCheckedChildren;
            try {
                await remote(params, checked);
                setIsChecked(checked);
                setIsLoading(false);
                setIsDisabled(false);
                onSuccess && onSuccess(checked);
                if (!isNotSuccessAlt) {
                    message.success(`${promptMsg}成功`);
                }
            } catch (error: any) {
                setIsLoading(false);
                setIsDisabled(false);
                onFail && onFail(checked, error);
                if (!isNotFailAlt) {
                    message.error(`${promptMsg}失败`);
                }
            }
        }
    }

    return (
        <Switch
            loading={isLoading}
            onClick={handleClick}
            onChange={handleChange}
            checked={isChecked}
            disabled={isDisabled}
            checkedChildren={checkedChildren}
            unCheckedChildren={unCheckedChildren}
        />
    )
}

export default RemoteSwitch;